//
//  GAOComposePictureView.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

let PictureViewCellReuseIdentifier = "PictureViewCellReuseIdentifier"
class GAOComposePictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
    
    //  点击加号按钮的闭包
    var didSelectAddImageClosure: (()->())?

    //  保存添加图片
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        hidden = true
        //  注册cell
        registerClass(GAOComposePictureViewCell.self, forCellWithReuseIdentifier: PictureViewCellReuseIdentifier)
        dataSource = self
        delegate = self
//        backgroundColor = 
    }
    
    func addImage(image: UIImage) {
        hidden = false
        images.append(image)
        reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  每项间距
        let itemMargin: CGFloat = 5
        //  计算每项宽度
        let itemWidth = (frame.size.width - 2 * itemMargin) / 3
        //  获取布局对象
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置间距
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        
    }
    
    //  MARK:   - UICollectionViewDataSource实现代理方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = images.count
        
        if count == 0 || count == 9 {
            return count
        }else {
            return count + 1
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureViewCellReuseIdentifier, forIndexPath: indexPath) as! GAOComposePictureViewCell
//        cell.backgroundColor = RandomColor()
        //判断当前item小于数组个数,可以取值,防止数组越界
        if indexPath.item < images.count {
            cell.image = images[indexPath.item]
        }else {
            //显示加号按钮
            cell.image = nil
        }
        //设置删除image的闭包
        cell.deleteButtonClosure = {[weak self] in
            self?.images.removeAtIndex(indexPath.item)
            
            //删除全部image后隐藏pictureView
            if self?.images.count == 0 {
                self?.hidden = true
            }
            
            self?.reloadData()
        }
        
        
        
        return cell
    }
    
    //  MARK: UICollectionViewDelegate 实现方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //如果当前item的索引等于数组个数,则此item是加号按钮
        if indexPath.item == images.count {
            print("加号按钮")
            didSelectAddImageClosure?()
        }
    }
    
}






//自定义cell
class GAOComposePictureViewCell: UICollectionViewCell {
    //点击删除按钮的闭包
    var deleteButtonClosure: (() -> ())?
    
    //接收外界传来的图片
    var image: UIImage? {
        didSet {
            if image == nil {
                //显示加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                //添加高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                //隐藏deleteImageButton
                deleteImageButton.hidden = true
                
            }else {
                //设置图片
                imageView.image = image
                imageView.highlightedImage = nil
                
                //显示deleteImageButton
                deleteImageButton.hidden = false
            }
            
        }
    }
    
    //  MARK: 懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    
    private lazy var deleteImageButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        button.addTarget(self, action: "deleteImageButtonAction", forControlEvents: .TouchUpInside)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteImageButton)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deleteImageButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
        
    }
    
    @objc private func deleteImageButtonAction() {
        deleteButtonClosure? ()
    }
}

